package com.note.back.controller;

import com.note.back.pojo.Note;
import com.note.back.pojo.Result;
import com.note.back.pojo.User;
import com.note.back.service.CategoryService;
import com.note.back.service.LLMService;
import com.note.back.service.NoteService;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;


@RestController
@RequestMapping("/note")
public class NoteController {

    @Autowired
    NoteService noteService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    LLMService llmService;

    @PostMapping("/create/{category}")
    public Result add(@PathVariable String category,@RequestBody Note note){
        note.setCategory(Integer.valueOf(category));
        noteService.add(note);
        return Result.success("添加笔记成功");
    }

    @GetMapping("/search")
    public Result<List<Note>> list(@RequestBody Map<String,String> params){
        String title = params.get("title");
        String category = params.get("category");
        String startTime = params.get("startTime");
        String endTime = params.get("endTime");
        String timeType = params.get("timeType");

        //根据标题查询
        List<Note> list1;
        if(Objects.equals(title, "")){
            list1 = noteService.list();
        }else {
            list1 = noteService.searchTitle(title);
        }
        //根据分类查询
        List<Note> list2;
        if(Objects.equals(category, "")){
            list2 = noteService.list();
        }else {
            Integer categoryId = categoryService.findByName(category);
            list2 = noteService.searchCategory(categoryId);
        }
        //根据时间查询
        List<Note> list3 = null;
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        if (Objects.equals(startTime, "") || startTime == null) {
            startTime = LocalDateTime.of(2025, 1, 1, 0, 0, 0).format(formatter);
        }
        if (Objects.equals(endTime, "") || endTime == null) {
            endTime = LocalDateTime.now().format(formatter);
        }
        if (Objects.equals(timeType, "") || timeType == null) {
            timeType = "createTime";
        }
        if (timeType.equals("createTime")) {
            list3 = noteService.searchCreateTime(startTime, endTime);
        } else if (timeType.equals("updateTime")) {
            list3 = noteService.searchUpdateTime(startTime, endTime);
        }
        if(list1==null || list2==null || list3==null){
            return Result.success(null,"笔记已就绪");
        }
        List<Note> list = list1;
        list.retainAll(list2);
        list.retainAll(list3);
        return Result.success(list,"笔记已就绪");
    }

    @PostMapping("/update/{id}")
    public Result update(@PathVariable String id,@RequestBody Note note){
        note.setId(Integer.valueOf(id));

        note.setCategory(noteService.findById(Integer.valueOf(id)).getCategory());
        noteService.update(note);
        return Result.success("笔记信息修改成功");
    }

    @GetMapping("/detail/{id}")
    public Result detail(@PathVariable String id){
        Note note = noteService.findById(Integer.valueOf(id));
        return Result.success(note,"笔记查看成功");
    }

    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable String id){
        noteService.delete(Integer.valueOf(id));
        return Result.success("笔记删除成功");
    }

    @GetMapping("/search/title")
    public Result<List<Note>> title(@RequestParam(required = false) String title){
        List<Note> list1;
        System.out.println(title);
        if(Objects.equals(title, "") || title == null){
            list1 = noteService.list();
        }else {
            list1 = noteService.searchTitle(title);
        }
        return Result.success(list1,"标题查询成功");
    }

    @GetMapping("/search/category/{id}")
    public Result<List<Note>> category(@PathVariable String id){
        List<Note> list2;

        Integer categoryId = Integer.valueOf(id);
        list2 = noteService.searchCategory(categoryId);

        return Result.success(list2,"分类笔记查询成功");
    }

    @GetMapping("/search/time")
    public Result<List<Note>> time(@RequestParam(required = false) String startTime, @RequestParam(required = false) String endTime,@RequestParam(required = false) String timeType){
        List<Note> list3 = null;
        // 定义时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        if (Objects.equals(startTime, "") || startTime == null) {
            startTime = LocalDateTime.of(2025, 1, 1, 0, 0, 0).format(formatter);
        }
        if (Objects.equals(endTime, "") || endTime == null) {
            endTime = LocalDateTime.now().format(formatter);
        }
        if (Objects.equals(timeType, "") || timeType == null) {
            timeType = "createTime";
        }
        if (timeType.equals("createTime")) {
            list3 = noteService.searchCreateTime(startTime, endTime);
        } else if (timeType.equals("updateTime")) {
            list3 = noteService.searchUpdateTime(startTime, endTime);
        }
        return Result.success(list3, "查询类型错误");
    }

    @PostMapping("/save/{id}")
    public Result save(@PathVariable String id,@RequestBody Note note){
        note.setId(Integer.valueOf(id));
        noteService.save(note);
        return Result.success("保存笔记正文成功");
    }

    //后面改为传入选中的文字
    @PostMapping("/continue")
    public Result<String> continueNote(@RequestBody Map<String,String> params) throws IOException {
        String requestText = params.get("requestText");
        String content = llmService.continuation(requestText);
        return Result.success(content,"大模型续写成功");
    }

    @PostMapping("/autoCategorize/{id}")
    public Result categorizeNote(@PathVariable String id) throws IOException {
        Note note = noteService.findById(Integer.valueOf(id));
        User user = (User)SecurityUtils.getSubject().getPrincipal();

        String category = llmService.categorize(user, note.getContentMd());
        //Integer categoryId = categoryService.findByName(category);
        note.setCategory(Integer.valueOf(category));
        noteService.update(note);
        return Result.success("自动分类成功");
    }

//    final static String PIC_PATH = "static/pics/";
//
//    @CrossOrigin
//    @PostMapping("/api/pic")
//    @ResponseBody
//    public Response uploadPic(MultipartHttpServletRequest multiRequest, HttpServletRequest request){
//        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
//        String datePrefix = dateFormat.format(new Date());
//        String savePath = "src/main/resources/"+PIC_PATH;
//
//        File folder = new File(savePath+datePrefix);
//        if(!folder.isDirectory()){
//            folder.mkdirs();
//        }
//        String originalName = multiRequest.getFile("image").getOriginalFilename();
//        String saveName = UUID.randomUUID().toString() + originalName.substring(originalName.lastIndexOf("."),originalName.length());
//        String absolutePath = folder.getAbsolutePath();
//
//        try{
//            File fileToSave = new File(absolutePath + File.separator + saveName);
//            multiRequest.getFile("image").transferTo(fileToSave);
//            String returnPath = request.getScheme() + "://"
//                    + request.getServerName()+":"+request.getServerPort()
//                    +"/article/images/"
//                    + datePrefix +"/"+ saveName;
//
//            return new Response(200,"上传成功",returnPath);
//        }catch (Exception e){
//            e.printStackTrace();
//        }
//        return new Response(500,"上传失败",null);
//
//    }
}
